//
//  RGMainPageView.m
//  RedGrass
//
//  Created by wukong on 2018/11/25.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGMainPageView.h"
#import "RGMainPageListCell.h"
#import "RGMainPageNavView.h"
#import "RGRecommendVideoModel.h"
#import "GKDYVideoPlayer.h"
#import <MJRefresh.h>
//#import "RGBottomCommentToolBar.h"


@interface RGMainPageView()<UITableViewDelegate, UITableViewDataSource,GKDYVideoPlayerDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) RGMainPageNavView *navView;
@property (strong, nonatomic) MJRefreshNormalHeader *freshHeader;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *freshFooter;
@property (strong, nonatomic) NSMutableArray *vedioList;
@property (assign, nonatomic) NSInteger currentIndex;
@property (strong, nonatomic) GKDYVideoPlayer *vedioPlayer;
@property (assign, nonatomic) NSInteger vediolListCount;
@property (assign, nonatomic) BOOL isShowToolBar;

//@property (strong, nonatomic) RGBottomCommentToolBar *bottomCommentToolBar;


@end

@implementation RGMainPageView

-(instancetype)initViewWithIsShowBottomToolBar:(BOOL)isShowToolBar{
    if(self = [super init]){
        _isShowToolBar = isShowToolBar;
    }
    return self;
}

-(instancetype) initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        _currentIndex = -1;
        _vediolListCount = 0;
        [self addObserver:self forKeyPath:@"currentIndex" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
        self.backgroundColor = UICOLOR_WITH_RGBINT_A(0x000000, 0.3);
        [self addSubview:self.tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
        [self addSubview:self.navView];
        [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self).mas_offset(32);
            make.left.and.right.mas_equalTo(self).mas_offset(0);
            make.height.mas_equalTo(50);
        }];
    }
    return self;
}

#pragma tableView delegate


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_vedioList count];
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScreenHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //填充视频数据
    RGMainPageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RGMainPageListCell" forIndexPath:indexPath];
    cell.isShowBottomToolBar = _isShowToolBar;
    RGRecommendVideoModel *model = _vedioList[indexPath.row];
    if(model){
        cell.videoModel = model;
    }
    AA_WEAK_MAKE(self)weakSelf = self;
    [cell setActionItemClickBlock:^(NSInteger tag) {
        if(tag == kAwemeListLikeCommentTag){//评论
            if([weakSelf.viewDelegate respondsToSelector:@selector(commentWithView:selectedPath:)]){
                [weakSelf.viewDelegate commentWithView:weakSelf selectedPath:indexPath];
            }
        }else if(tag == kAwemeListLikeShareTag){//分享
            if([weakSelf.viewDelegate respondsToSelector:@selector(shareWithView:selectedPath:)]){
                [weakSelf.viewDelegate shareWithView:weakSelf selectedPath:indexPath];
            }
        }else if (tag == kAwemeListLikeFocusTag){//关注
            if([weakSelf.viewDelegate respondsToSelector:@selector(focusWithView:selectedPath:)]){
                [weakSelf.viewDelegate focusWithView:weakSelf selectedPath:indexPath];
            }
        }else if (tag == kAwemeListLikeFavoriteTag){//喜欢
            if([weakSelf.viewDelegate respondsToSelector:@selector(favoriteWithView:selectedPath:)]){
                [weakSelf.viewDelegate favoriteWithView:weakSelf selectedPath:indexPath];
            }
            
        }else if (tag == kAwemeListVedioViewTapTag){//点击了视频区域
            [weakSelf updateCellVedioPlayStatusWithIndexPath:indexPath];
        }else if (tag == kAwemeListLikeUserIconTag){//点击了用户头像
            
            if([weakSelf.viewDelegate respondsToSelector:@selector(userIconClickWithCellIndex:)]){
                [weakSelf.viewDelegate userIconClickWithCellIndex:indexPath.row];
            }
        }
    }];
    return cell;
}

#pragma mark - public

-(NSInteger) currentShowCellIndex{
    return _currentIndex;
}

-(void) showBottomCommentToolBar{
//    [self addSubview:self.bottomCommentToolBar];
//    [_bottomCommentToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.right.mas_equalTo(self).mas_offset(0);
//        make.height.mas_equalTo(50);
//        make.bottom.mas_equalTo(self).mas_offset(0);
//    }];
}

-(void) hideCustomNavgationBar{
    self.navView.hidden = YES;
}

-(void) reloadTableViewWithVedioList:(NSMutableArray *)vedioList{
    if([vedioList count] == 0){
        return;
    }
    _vediolListCount = vedioList.count;
    _vedioList = vedioList;
    [self.tableView reloadData];
}

-(void) reloadTableViewWithVedioList:(NSMutableArray *)vedioList chosedIndex:(NSInteger)chosedIndex{
    _vediolListCount = vedioList.count;
    _vedioList = vedioList;
    AA_WEAK_MAKE(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        if(chosedIndex == 0){
             weakSelf.currentIndex = chosedIndex;
        }else if(chosedIndex <= vedioList.count - 1){
           
            weakSelf.tableView.panGestureRecognizer.enabled = NO;
            [UIView animateWithDuration:0.2
                                  delay:0.0
                                options:UIViewAnimationOptionCurveEaseOut animations:^{
                                    //UITableView滑动到指定cell
                                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:chosedIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                                } completion:^(BOOL finished) {
                                    //UITableView可以响应其他滑动手势
                                    weakSelf.currentIndex = chosedIndex;
                                    weakSelf.tableView.panGestureRecognizer.enabled = YES;
                                }];
            
        }
        NSLog(@",currentIndex = %ld",weakSelf.currentIndex);
    });
}


-(void) reloadTableViewWhenHaveMoreVedioWithVedioList:(NSMutableArray *)vedioList{
    if([vedioList count] == 0){
        return;
    }
    _vediolListCount = vedioList.count;
    _vedioList = vedioList;
//    NSMutableArray<NSIndexPath *> *indexPaths = [NSMutableArray array];
//    for(NSInteger row = _currentIndex + 1; row< self.vedioList.count; row++) {
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
//        [indexPaths addObject:indexPath];
//    }
//    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:NO];
//    [self.tableView endUpdates];
    
      AA_WEAK_MAKE(self) weakSelf = self;
     dispatch_async(dispatch_get_main_queue(), ^{
         [self.tableView reloadData];
          weakSelf.currentIndex ++;
        if(weakSelf.currentIndex < vedioList.count - 1){
            weakSelf.tableView.panGestureRecognizer.enabled = NO;
            [UIView animateWithDuration:0.2
                                  delay:0.0
                                options:UIViewAnimationOptionCurveEaseOut animations:^{
                                    //UITableView滑动到指定cell
                                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                                } completion:^(BOOL finished) {
                                    //UITableView可以响应其他滑动手势
                                    
                                      weakSelf.tableView.panGestureRecognizer.enabled = YES;
                                }];
        
        }
        NSLog(@",currentIndex = %ld",weakSelf.currentIndex);
     });
}


-(void) playVedioWithFirstIndexWhenLoadSuccess{
    
    self.currentIndex = 0;
//    if([_vedioList count]){
//         RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
//        [cell vedioPlay];
//    }
//
}


-(void) setMainPageViewMjFooterStatusWithNoMoreData{
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    _freshFooter.state = MJRefreshStateNoMoreData;
}

-(void) mainPageViewMjHeaderLoadingEnd{
    [_freshHeader endRefreshing];
}

-(void) mainPageViewMjFooterLoadingEnd{
    [_freshFooter endRefreshing];
}


-(void) stopPlayingWhenCurrentVCIsNoteVisiable{
    if([_vedioPlayer isPlaying]){
        [_vedioPlayer pausePlay];
    }
}

-(void) startFocusAnimationWithIsFocus:(BOOL)isFoucus cellIndex:(NSInteger)index{
    
    RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    NSArray *cells = [self.tableView visibleCells];
    for (RGMainPageListCell *tempCell in cells) {
         RGRecommendVideoModel *model = tempCell.videoModel;
        if(model.ID != cell.videoModel.ID){
            if(tempCell.videoModel.videoUser.ID == cell.videoModel.videoUser.ID){
                [tempCell begainFocusAnimationWithIsFocus:isFoucus];
            }
        }
    }
    
    for(int i = 0; i < _vedioList.count;i++) {
        RGRecommendVideoModel *model = _vedioList[i];
        if (model.videoUser.ID == cell.videoModel.videoUser.ID) {
            model.videoUser.meFollowmTa = isFoucus;
        }
    }
    if(index != _currentIndex){
        return;
    }
    [cell begainFocusAnimationWithIsFocus:isFoucus];
}

-(void) startFavoriteAnimationWithIsFavorite:(BOOL)isFavorite cellIndex:(NSInteger)index{
    if(index != _currentIndex){
        return;
    }
    RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    [cell begainFavoriteAnimationWithIsFavorite:isFavorite];
}


//评论成功后，更新视图里面的评论数
-(void) updateCommentCountsWhenCommentSuccessWithCellIndex:(NSInteger)cellIndex{
     RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    [cell updateCommentCounts];
}

-(void)updateforwardCountsWhenShareSuccessWithCellIndex:(NSInteger)cellIndex{
    RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    [cell  updateForwardCounts];
}



#pragma mark - scrollView delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    dispatch_async(dispatch_get_main_queue(), ^{
        CGPoint translatedPoint = [scrollView.panGestureRecognizer translationInView:scrollView];
        //UITableView禁止响应其他滑动手势
        scrollView.panGestureRecognizer.enabled = NO;
        NSLog(@"y= %f", translatedPoint.y);
        if(translatedPoint.y < -50 && self.currentIndex < (self.vediolListCount - 1)) {
            self.currentIndex ++;   //向下滑动索引递增
        }
        if(translatedPoint.y > 50 && self.currentIndex > 0) {
            self.currentIndex --;   //向上滑动索引递减
        }
        if(self.currentIndex >= 0){
            if(self.currentIndex < self.vediolListCount){
                [UIView animateWithDuration:0.15
                                      delay:0.0
                                    options:UIViewAnimationOptionCurveEaseOut animations:^{
                                        //UITableView滑动到指定cell
                                        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                                    } completion:^(BOOL finished) {
                                        //UITableView可以响应其他滑动手势
                                        scrollView.panGestureRecognizer.enabled = YES;
                                    }];
                if([self.viewDelegate respondsToSelector:@selector(updateTabbarUIStyleWithCellIndex:)]){
                    [self.viewDelegate updateTabbarUIStyleWithCellIndex:self.currentShowCellIndex];
                }
            }else{
               scrollView.panGestureRecognizer.enabled = YES;
            }
         
        }else{
            scrollView.panGestureRecognizer.enabled = YES;
        }
       
     
       
        NSLog(@"tyyyy = %ld,%ld",self.currentIndex,self.vediolListCount);
    });
}

//观察currentIndex变化
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentIndex"]) {
        //设置用于标记当前视频是否播放的BOOL值为NO
//        _isCurPlayerPause = NO;
        //获取当前显示的cell
        if(_currentIndex >= 0){
            RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
//            __weak typeof (cell) wcell = cell;
//            __weak typeof (self) wself = self;
//            [cell vedioPlay];
            [_vedioPlayer removeVideo];
            cell.isShowPauseAnimation = YES;
            [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
            if([self.viewDelegate respondsToSelector:@selector(updateVedioPlayCountWithCellIndex:)]){
                [self.viewDelegate updateVedioPlayCountWithCellIndex:_currentIndex];
            }
        }
    } else {
        return [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

//更新当前cell的视频播放状态
-(void) updateCellVedioPlayStatusWithIndexPath:(NSIndexPath *)path{
//     RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
        [_vedioPlayer pausePlay];
//        cell.isShowPauseAnimation = YES;
    }else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
        [_vedioPlayer resumePlay];
//        cell.isShowPauseAnimation = NO;
    }
    
}

- (void)player:(GKDYVideoPlayer *)player statusChanged:(GKDYVideoPlayerStatus)status{
    RGMainPageListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]];
    if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
        cell.isShowPauseAnimation = NO;
    }else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
        cell.isShowPauseAnimation = YES;
    }
}


#pragma mark -response

-(void)loadVedio{
    if([self.viewDelegate respondsToSelector:@selector(gainRecommendVideoListWithView:isLoadMore:)]){
        [self.viewDelegate gainRecommendVideoListWithView:self isLoadMore:NO];
    }
}

-(void)loadMoreVedio{
    if([self.viewDelegate respondsToSelector:@selector(gainRecommendVideoListWithView:isLoadMore:)]){
        [self.viewDelegate gainRecommendVideoListWithView:self isLoadMore:YES];
    }
}



#pragma mark - getter

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
//        _tableView.contentInset = UIEdgeInsetsMake(KScreenHeight, 0, KScreenWidth * 3, 0);
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:RGMainPageListCell.class forCellReuseIdentifier:@"RGMainPageListCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
//            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.mj_header = self.freshHeader;
        _tableView.mj_footer = self.freshFooter;
    }
    return _tableView;
}

-(MJRefreshNormalHeader *)freshHeader{
    if(!_freshHeader){
        _freshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadVedio)];
       _freshHeader.automaticallyChangeAlpha = YES;
    }
    return _freshHeader;
}

-(MJRefreshAutoNormalFooter *)freshFooter{
    if(!_freshFooter){
        _freshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreVedio)];
        [_freshFooter setTitle:@"暂时没有更多了" forState:MJRefreshStateNoMoreData];
//        _freshFooter.automaticallyChangeAlpha = YES;
    }
    return _freshFooter;
}

-(RGMainPageNavView *)navView {
    if(!_navView){
        _navView = [[RGMainPageNavView alloc]init];
        AA_WEAK_MAKE(self)weakSelf = self;
        [_navView setNavViewBtnClickBlock:^(NSInteger tag) {
            if(tag == kMainPageQRCodeScanTag){//扫描
                if([weakSelf.viewDelegate respondsToSelector:@selector(scanQRCodeWithView:)]){
                    [weakSelf.viewDelegate scanQRCodeWithView:weakSelf];
                }
            }else if (tag == kMainPageSearchTag){//搜索
                if([weakSelf.viewDelegate respondsToSelector:@selector(searchSomethingWithView:)]){
                    [weakSelf.viewDelegate searchSomethingWithView:weakSelf];
                }
            }
        }];
    }
    return _navView;
}

-(GKDYVideoPlayer *)vedioPlayer{
    if(!_vedioPlayer){
        _vedioPlayer = [[GKDYVideoPlayer alloc]init];
        _vedioPlayer.renderMode = RENDER_MODE_FILL_EDGE;
        _vedioPlayer.delegate = self;
    }
    return _vedioPlayer;
}

//-(RGBottomCommentToolBar *) bottomCommentToolBar{
//    if(!_bottomCommentToolBar){
//        _bottomCommentToolBar = [[RGBottomCommentToolBar alloc]init];
//    }
//    return _bottomCommentToolBar;
//}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"currentIndex"];
}

@end
